
import Vue from 'vue'
import { throttle } from '@/utils/throttle.js'

Vue.directive('scroll', {
  bind (el, binding) {
    const exprArr = binding.expression.replace(/{/, '').replace(/}/, '').split(/,|:/)
    let i = 0
    const exprObj = {}
    while (i < exprArr.length) {
      const [key, value] = [exprArr[i], exprArr[i + 1]]
      exprObj[key] = value
      i += 2
    }
    const request = exprObj['request']
    const page = exprObj['current_page']
    const lastPage = exprObj['last_page']
    const that = binding.value['that']
    console.log(el)
    console.log(el.scroll_handler)
    el.scroll_handler = throttle((e) => {
      const { scrollTop, scrollHeight, clientHeight } = e.target
      console.log(e)
      if (scrollTop + clientHeight >= scrollHeight) {
        if (that[lastPage] < that[page] && el.scroll_handler) {
          el.removeEventListener('scroll', el.scroll_handler)
          el.scroll_handler = null
        } else {
          that[request] && that[request]().then((res) => {
            console.log(res)
            // lastPage = res.data.last_page
          })
        }
      }
    }, 200, 300)
    el.addEventListener('scroll', el.scroll_handler)
  },
  unbind (el) {
    console.log(7777777)
    if (el.scroll_handler) {
      console.log(6666)
      el.removeEventListener('scroll', el.scroll_handler)
      el.scroll_handler = null
    }
  }
})
